<template>
  <view class="container">
    <!-- 页面头部 -->
    <view class="header">
      <view class="header-left" @click="goBack">
        <text class="back-icon">←</text>
        <text class="back-text">返回</text>
      </view>
      <text class="header-title">投资记录详情</text>
      <view class="header-right"></view>
    </view>

    <!-- 详情内容区域 -->
    <view class="detail-content">
      <!-- 投资类别标签 -->
      <view class="category-tag">
        <text class="category-icon">{{ getCategoryIcon(record.category) }}</text>
        <text class="category-name">{{ getCategoryLabel(record.category) }}</text>
      </view>

      <!-- 金额展示 -->
      <view class="amount-section">
        <text class="amount-label">投资金额</text>
        <text class="amount-value">{{ record.cny.toFixed(2) }} CNY</text>
      </view>

      <!-- 详细信息列表 -->
      <view class="info-list">
        <view class="info-item">
          <text class="info-label">投资日期</text>
          <text class="info-value">{{ formatFullDate(record.date) }}</text>
        </view>
        <!-- 定存特殊字段 -->
        <view v-if="record.category === '定存'" class="fixed-deposit-section">
          <view class="info-item">
            <text class="info-label">起始日期</text>
            <text class="info-value">{{ record.deposit_start_date ? formatFullDate(record.deposit_start_date) : '未设置' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">金额</text>
            <text class="info-value">{{ record.cny.toFixed(2) }} CNY</text>
          </view>
          <view class="info-item">
            <text class="info-label">年化利率</text>
            <text class="info-value">{{ record.deposit_rate ? (record.deposit_rate).toFixed(2) + '%' : '未设置' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">存款期限</text>
            <text class="info-value">{{ record.deposit_duration ? record.deposit_duration + ' 个月' : '未设置' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">预计到期日</text>
            <text class="info-value">{{ getMaturityDate(record) }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">预计利息</text>
            <text class="info-value profit-text">{{ calculateInterest(record).toFixed(2) }} CNY</text>
          </view>
          <view class="info-item">
            <text class="info-label">预计本息和</text>
            <text class="info-value profit-text">{{ calculateTotalAmount(record).toFixed(2) }} CNY</text>
          </view>
        </view>
        <view class="info-item">
          <text class="info-label">记录ID</text>
          <text class="info-value">{{ record.id }}</text>
        </view>
        <view class="info-item" v-if="record.usd && record.usd > 0">
          <text class="info-label">美元金额</text>
          <text class="info-value">{{ record.usd.toFixed(2) }} USD</text>
        </view>
        <view class="info-item" v-if="record.exchange_rate && record.exchange_rate > 0">
          <text class="info-label">汇率</text>
          <text class="info-value">{{ record.exchange_rate.toFixed(2) }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">创建时间</text>
          <text class="info-value">{{ formatFullDate(record.created_at) }}</text>
        </view>
        <view class="info-item" v-if="record.updated_at">
          <text class="info-label">更新时间</text>
          <text class="info-value">{{ formatFullDate(record.updated_at) }}</text>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button class="btn-edit" @click="editRecord">编辑记录</button>
        <button class="btn-delete" @click="deleteRecord">删除记录</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { baseDel } from '../../utils/api';

const router = useRouter();
const route = useRoute();

// 记录数据
const record = ref({
  id: '',
  date: '',
  cny: 0,
  category: '',
  usd: 0,
  exchange_rate: 0,
  deposit_start_date: '',
  deposit_duration: null,
  deposit_rate: null,
  created_at: '',
  updated_at: ''
});

// 页面加载时获取记录数据
onMounted(() => {
  // 从路由参数中获取记录ID
  const recordId = route.query.id;
  if (recordId) {
    // 优先从路由参数中获取记录数据
    record.value = {
      id: recordId,
      date: route.query.date || '',
      cny: parseFloat(route.query.cny) || 0,
      category: route.query.category || '',
      usd: parseFloat(route.query.usd) || 0,
      exchange_rate: parseFloat(route.query.exchange_rate) || 0,
      deposit_start_date: route.query.deposit_start_date || '',
      deposit_duration: route.query.deposit_duration ? parseInt(route.query.deposit_duration) : null,
      deposit_rate: route.query.deposit_rate ? parseFloat(route.query.deposit_rate) : null,
      created_at: route.query.created_at || '',
      updated_at: route.query.updated_at || ''
    };
    
    // 更新本地存储，确保下次加载时使用最新数据
    uni.setStorageSync(`record_${recordId}`, JSON.stringify(record.value));
  }
});

// 返回上一页
const goBack = () => {
  // 直接跳转到history页面，避免页面栈问题导致的错误跳转
  router.push('/pages/history/history');
};

// 获取投资类别标签
const getCategoryLabel = (category) => {
  const categoryMap = {
    '货币基金': '货币基金',
    '定存': '定存',
    '基金': '基金',
    '股票': '股票',
    '黄金': '黄金',
    '虚拟币': '虚拟币'
  };
  return categoryMap[category] || category;
};

// 获取投资类别图标
const getCategoryIcon = (category) => {
  const iconMap = {
    '货币基金': '💰',
    '定存': '🏦',
    '基金': '📈',
    '股票': '📊',
    '黄金': '🥇',
    '虚拟币': '🪙'
  };
  return iconMap[category] || '📝';
};

// 格式化完整日期显示
const formatFullDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 格式化日期（仅日期，不含时间）
const formatDateOnly = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 计算定存到期日
const getMaturityDate = (record) => {
  if (!record.deposit_start_date || !record.deposit_duration) {
    return '无法计算';
  }
  
  const startDate = new Date(record.deposit_start_date);
  startDate.setMonth(startDate.getMonth() + record.deposit_duration);
  
  return formatDateOnly(startDate.toISOString());
};

// 计算定存利息
const calculateInterest = (record) => {
  if (!record.deposit_rate || !record.deposit_duration) {
    return 0;
  }
  
  // 简单利息计算公式：利息 = 本金 × 年利率 × 时间（年）
  // 注意：数据库中存储的是百分比形式的利率，需要除以100
  const years = record.deposit_duration / 12;
  const interest = record.cny * (record.deposit_rate / 100) * years;
  
  return interest;
};

// 计算定存本息和
const calculateTotalAmount = (record) => {
  return record.cny + calculateInterest(record);
};

// 编辑记录
const editRecord = () => {
  router.push({
    path: '/pages/history/add',
    query: {
      mode: 'edit',
      ...record.value
    }
  });
};

// 删除记录
const deleteRecord = async () => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条投资记录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          // 调用后端API删除记录
          const result = await baseDel(`/investment-history/${record.value.id}`);
          
          if (result.statusCode === 200 && result.data.success) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
            // 删除成功后返回上一页
            setTimeout(() => {
              router.back();
            }, 1500);
          } else {
            uni.showToast({
              title: result.data?.error || '删除失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('删除记录失败:', error);
          if (error.message !== '未登录') {
            uni.showToast({
              title: '网络错误，删除失败',
              icon: 'none'
            });
          }
        }
      }
    }
  });
};
</script>

<style>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  padding: 0;
  background-color: #f5f5f5;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

/* 页面头部样式 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #FFFFFF;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
}

.back-icon {
  font-size: 18px;
  margin-right: 4px;
}

.back-text {
  font-size: 16px;
  color: #333333;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333333;
}

.header-right {
  width: 40px;
}

/* 详情内容样式 */
.detail-content {
  padding: 20px;
  background-color: #FFFFFF;
  margin-bottom: 10px;
}

/* 类别标签样式 */
.category-tag {
  display: inline-flex;
  align-items: center;
  padding: 8px 16px;
  background-color: #f0f0f0;
  border-radius: 20px;
  margin-bottom: 24px;
}

.category-icon {
  font-size: 20px;
  margin-right: 8px;
}

.category-name {
  font-size: 16px;
  color: #333333;
}

/* 金额展示样式 */
.amount-section {
  text-align: center;
  margin-bottom: 32px;
}

.amount-label {
  display: block;
  font-size: 14px;
  color: #666666;
  margin-bottom: 8px;
}

.amount-value {
  display: block;
  font-size: 32px;
  font-weight: 700;
  color: #333333;
}

/* 信息列表样式 */
.info-list {
  border-top: 1px solid #eeeeee;
  margin-bottom: 32px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #eeeeee;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 14px;
  color: #666666;
}

.info-value {
  font-size: 14px;
  color: #333333;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.btn-edit {
  background-color: #007AFF;
  color: #FFFFFF;
  border: none;
  border-radius: 8px;
  padding: 14px 0;
  font-size: 16px;
  font-weight: 600;
}

.btn-delete {
  background-color: #FF3B30;
  color: #FFFFFF;
  border: none;
  border-radius: 8px;
  padding: 14px 0;
  font-size: 16px;
  font-weight: 600;
}
</style>